package com.tfswx.jcyw.dmzc.window;

import com.intellij.openapi.ui.DialogWrapper;
import com.tfswx.jcyw.dmzc.api.dto.RylbQueryResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class SelectRy extends DialogWrapper {
    private final List<RylbQueryResult> list;
    private JPanel contentPane;
    private JList<RylbQueryResult> ryList;
    private JTextField gjz;

    public SelectRy(List<RylbQueryResult> list, Consumer<RylbQueryResult> cb) {
        super(false);
        this.list = list;
        init();
        setTitle("选择开发人员（双击选择）");
        gjz.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                reloadDate();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                reloadDate();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                reloadDate();
            }
        });

        DefaultListModel<RylbQueryResult> defaultListModel = new DefaultListModel<>();
        ryList.setModel(defaultListModel);
        ryList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    RylbQueryResult selectedValue = ryList.getSelectedValue();
                    cb.accept(selectedValue);
                    close(OK_EXIT_CODE);
                }
            }
        });
        reloadDate();
    }

    @Override
    protected Action @NotNull [] createActions() {
        return new Action[0];
    }

    private void reloadDate() {
        DefaultListModel<RylbQueryResult> defaultListModel = (DefaultListModel<RylbQueryResult>) ryList.getModel();
        List<RylbQueryResult> collect = list.stream().filter(item -> {
            boolean contains = item.getRymc().toLowerCase().contains(gjz.getText().toLowerCase());
            if (contains) {
                return true;
            }
            for (String s : item.getPy()) {
                if (s.contains(gjz.getText().toLowerCase().toLowerCase())) {
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        defaultListModel.clear();
        defaultListModel.addAll(collect);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return contentPane;
    }
}
